import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './router'
import store from '../store/index'
import { getCookie } from '@/utils/aqi'

Vue.use(VueRouter)

const isCustomerPath = window.location.pathname.includes('/customer/web')
const basePath = isCustomerPath ? '/customer/web' : '/web/cmsview/crm' // 根据当前路径动态选择基础路径

const router = new VueRouter({
  mode: 'history',
  base: basePath, // 动态设置基础路径
  routes
})

// 封装添加路由
const addRout = (item) => {
  router.addRoutes(item)
}

// var num = 0
// router.beforeEach((to, from, next) => {
//   if (to.path === '/Login') {
//     next()
//   } else {
//     if (to.matched.length === 0) {
//       if (num < 4) {
//         setTimeout(() => {
//           addRout(store.state.module1.menu_list)
//           next({ ...to, replace: true })
//           num = num + 1
//         }, 500)
//       } else {
//         num = 0
//         if (getCookie('token')) {
//           // 根据当前路径判断跳转到正确的首页
//           if (window.location.pathname !== `${basePath}/Home`) {
//             window.location.href = `${basePath}/Home`
//           }
//         } else {
//           window.location.href = `${basePath}/Login`
//         }
//       }
//     } else {
//       next()
//     }
//   }
// })
router.beforeEach((to, from, next) => {
  // 如果是登录页面，直接放行
  if (to.path === '/Login') {
    next()
    return
  }

  // 检查路由是否匹配
  if (to.matched.length === 0) {
    handleUnmatchedRoute(to, next)
  } else {
    // 如果已匹配，直接放行
    next()
  }
})

// 处理未匹配路由逻辑的函数
let num = 0
const MAX_RETRY = 4

function handleUnmatchedRoute (to, next) {
  if (num < MAX_RETRY) {
    // 动态加载路由后重新尝试导航
    setTimeout(() => {
      addRout(store.state.module1.menu_list)
      next({ ...to, replace: true })
      num++
    }, 500)
  } else {
    // 超过最大尝试次数，重置计数器
    num = 0
    handleUnauthorizedAccess()
  }
}

// 处理未授权访问的逻辑
function handleUnauthorizedAccess () {
  const token = getCookie('token')

  if (token) {
    // 如果有 token，确保跳转到正确的首页
    const currentPath = window.location.pathname
    const homePath = `${basePath}/Home`
    if (currentPath !== homePath) {
      window.location.href = homePath
    }
  } else {
    // 如果没有 token，跳转到登录页面
    window.location.href = `${basePath}/Login`
  }
}

export default router
